/**
 * 亲密度展示组件
 * 显示用户当前身份、亲密度等级、解锁内容统计等信息
 */
import React, { useState, useEffect } from 'react'
import { View, Text, Button } from '@tarojs/components'
import Taro from '@tarojs/taro'
import { useAppContext } from '../../store'
import { identityUtils } from '../../utils/identityUtils'
import { IntimacyLevel } from '../../types/identity'
import './index.scss'

/**
 * 亲密度展示组件属性接口
 */
interface IntimacyDisplayProps {
  userId: string;           // 用户ID
  intimacy: number;         // 当前亲密度
  identitySubType: string;  // 身份子类型
  identityName: string;     // 身份名称
}

/**
 * 亲密度展示组件
 * 展示用户身份信息、亲密度进度、解锁内容统计等
 */
export default function IntimacyDisplay({
  userId,
  intimacy,
  identitySubType,
  identityName
}: IntimacyDisplayProps) {
  const { state } = useAppContext()
  const [upcomingUnlocks, setUpcomingUnlocks] = useState<any>({ specialDishes: [], stickerStories: [] })
  const [unlockedContents, setUnlockedContents] = useState<any>({ specialDishes: [], stickerStories: [] })
  const [loading, setLoading] = useState(true)

  // 组件挂载时加载解锁数据
  useEffect(() => {
    loadIntimacyData()
  }, [userId, intimacy, identitySubType])

  /**
   * 加载解锁数据
   * 获取即将解锁和已解锁的内容列表
   */
  const loadIntimacyData = async () => {
    try {
      setLoading(true)
      
      // 并行加载即将解锁和已解锁内容
      const [upcoming, unlocked] = await Promise.all([
        identityUtils.getUpcomingUnlocks(userId, intimacy, identitySubType),
        identityUtils.getUnlockedContents(userId)
      ])
      
      setUpcomingUnlocks(upcoming)
      setUnlockedContents(unlocked)
    } catch (error) {
      console.error('加载亲密度数据失败:', error)
    } finally {
      setLoading(false)
    }
  }

  /**
   * 获取亲密度等级名称
   * @param level 亲密度等级
   * @returns string 等级名称
   */
  const getIntimacyLevelName = (level: IntimacyLevel): string => {
    return identityUtils.getIntimacyLevelName(level)
  }

  /**
   * 获取亲密度等级对应的颜色
   * @param level 亲密度等级
   * @returns string 颜色值
   */
  const getIntimacyLevelColor = (level: IntimacyLevel): string => {
    switch (level) {
      case IntimacyLevel.STRANGER:
        return '#999'
      case IntimacyLevel.ACQUAINTANCE:
        return '#4CAF50'
      case IntimacyLevel.FRIEND:
        return '#2196F3'
      case IntimacyLevel.CLOSE:
        return '#FF9800'
      case IntimacyLevel.FAMILY:
        return '#F44336'
      default:
        return '#999'
    }
  }

  /**
   * 获取进度条颜色
   * @returns string 颜色值
   */
  const getProgressColor = (): string => {
    const level = identityUtils.getIntimacyLevel(intimacy)
    return getIntimacyLevelColor(level)
  }

  /**
   * 获取亲密度进度
   */
  const getIntimacyProgress = () => {
    const level = identityUtils.getIntimacyLevel(intimacy)
    const nextLevel = level + 1
    
    if (nextLevel > 4) {
      return { current: intimacy, max: intimacy, percentage: 100 }
    }
    
    const levelRanges = [0, 10, 30, 60, 100]
    const currentLevelMin = levelRanges[level]
    const nextLevelMin = levelRanges[nextLevel]
    
    const progress = intimacy - currentLevelMin
    const max = nextLevelMin - currentLevelMin
    
    return {
      current: progress,
      max,
      percentage: Math.min(100, (progress / max) * 100)
    }
  }

  const progress = getIntimacyProgress()

  /**
   * 查看已解锁内容
   */
  const handleViewUnlocked = () => {
    Taro.navigateTo({
      url: '/pages/identity/unlocked/index'
    })
  }

  /**
   * 查看即将解锁内容
   */
  const handleViewUpcoming = () => {
    Taro.navigateTo({
      url: '/pages/identity/upcoming/index'
    })
  }

  return (
    <View className='intimacy-display'>
      {/* 身份信息头部 */}
      <View className='identity-header'>
        <Text className='identity-name'>{identityName}</Text>
        <Text className='identity-level'>{getIntimacyLevelName(identityUtils.getIntimacyLevel(intimacy))}</Text>
      </View>

      {/* 亲密度进度条 */}
      <View className='intimacy-progress'>
        <View className='progress-info'>
          <Text className='progress-text'>亲密度</Text>
          <Text className='progress-score'>{intimacy}/100</Text>
        </View>
        
        <View className='progress-bar'>
          <View 
            className='progress-fill' 
            style={{ 
              width: `${(intimacy / 100) * 100}%`,
              backgroundColor: getProgressColor()
            }}
          />
        </View>
        
        <Text className='progress-level'>
          {getIntimacyLevelName(identityUtils.getIntimacyLevel(intimacy))}
        </Text>
      </View>

      {/* 解锁内容统计 */}
      <View className='unlock-stats'>
        <View className='stat-item'>
          <Text className='stat-number'>{unlockedContents.specialDishes.length}</Text>
          <Text className='stat-label'>已解锁菜品</Text>
        </View>
        <View className='stat-item'>
          <Text className='stat-number'>{unlockedContents.stickerStories.length}</Text>
          <Text className='stat-label'>已解锁故事</Text>
        </View>
        <View className='stat-item'>
          <Text className='stat-number'>{upcomingUnlocks.specialDishes.length + upcomingUnlocks.stickerStories.length}</Text>
          <Text className='stat-label'>即将解锁</Text>
        </View>
      </View>

      {/* 即将解锁内容预览 */}
      {!loading && (upcomingUnlocks.specialDishes.length > 0 || upcomingUnlocks.stickerStories.length > 0) && (
        <View className='upcoming-preview'>
          <Text className='preview-title'>即将解锁</Text>
          <View className='preview-list'>
            {upcomingUnlocks.specialDishes.slice(0, 2).map((dish: any) => (
              <View key={dish.id} className='preview-item'>
                <Text className='preview-icon'>{dish.icon}</Text>
                <View className='preview-info'>
                  <Text className='preview-name'>{dish.dishName}</Text>
                  <Text className='preview-progress'>还需 {dish.requiredIntimacy - intimacy} 亲密度</Text>
                </View>
              </View>
            ))}
            {upcomingUnlocks.stickerStories.slice(0, 2).map((story: any) => (
              <View key={story.id} className='preview-item'>
                <Text className='preview-icon'>{story.icon}</Text>
                <View className='preview-info'>
                  <Text className='preview-name'>{story.stickerName}</Text>
                  <Text className='preview-progress'>还需 {story.requiredIntimacy - intimacy} 亲密度</Text>
                </View>
              </View>
            ))}
          </View>
        </View>
      )}

      {/* 操作按钮 */}
      <View className='action-buttons'>
        <Button 
          className='action-btn unlocked-btn'
          onClick={handleViewUnlocked}
          disabled={unlockedContents.specialDishes.length === 0 && unlockedContents.stickerStories.length === 0}
        >
          查看已解锁
        </Button>
        <Button 
          className='action-btn upcoming-btn'
          onClick={handleViewUpcoming}
          disabled={upcomingUnlocks.specialDishes.length === 0 && upcomingUnlocks.stickerStories.length === 0}
        >
          查看即将解锁
        </Button>
      </View>

      {/* 亲密度获取提示 */}
      <View className='intimacy-tips'>
        <Text className='tips-title'>如何增加亲密度？</Text>
        <Text className='tips-item'>• 每次点餐 +2 亲密度</Text>
        <Text className='tips-item'>• 评价菜品 +1 亲密度</Text>
        <Text className='tips-item'>• 分享菜品 +1 亲密度</Text>
        <Text className='tips-item'>• 每日登录 +1 亲密度</Text>
        <Text className='tips-item'>• 特殊节日 +15 亲密度</Text>
      </View>
    </View>
  )
} 